package de.eventdroid.helper_classes;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONHandler {
	
	/* JSONObject for local handling*/
	private static JSONObject local_json_object = new JSONObject();	
	TextHandler local_text_handler = new TextHandler();
	/**
	 * 
	 * @param jsonToParse
	 * @param parserComponent
	 * @param fetchMultipleResults
	 * @return
	 */
	public static ArrayList<String> parseJSONDataForListView (String jsonToParse, String parserComponent, boolean fetchMultipleResults) {
		
		/* Parsing the Result within the Found Events into a JSON Object */
	    JSONArray JSONResultArray = null;
	    JSONObject aktJSONObject = null;
	    StringBuilder aktStringBuilder = null;
	    ArrayList<String> aktFoundObjectsForListViewArray = new ArrayList<String>();
	    String jSonArrayName = "";
	    
	    
		/* If a Event has to be parsed */
		if(parserComponent.equals("event")) {
		    
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "eventHandlerSet" :"eventHandler";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
					int event_id = aktJSONObject.getInt("event_id");
			        String event_name = aktJSONObject.getString("event_name");
			        String event_description = aktJSONObject.getString("event_description");
			        long event_start_date = aktJSONObject.getLong("event_start_date");
			        long event_start_time = aktJSONObject.getLong("event_start_time");	
			        
			        /* Format Date */
			        Date aktEventDate = new java.util.Date(event_start_date*1000);
			        SimpleDateFormat aktDateFormatter = new SimpleDateFormat("E dd MMM yyyy");
			        
			        /* Format Time */
			        int aktRessourceHours   = (int) ((event_start_time / 3600));
			        int aktRessourceMinutes = (int) ((event_start_time - (aktRessourceHours * 3600)) / 60 );
			        
			        /*Add missing hour because of GMT+1*/
			        aktRessourceHours += 1;
			        
			        /* Placeholder for Minutes converter in case of 0 Minutes */
			        String aktRessourceMinutesString = "";
			        
			        /* Check if minutes are 0, because in INT there is no possibility of Doubled zero */
			        aktRessourceMinutesString = aktRessourceMinutes == 0 ? "00" : aktRessourceMinutes+"";
			        
			        String aktRessourceStartTime = aktRessourceHours + ":" + aktRessourceMinutesString + " Uhr";
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(event_id + "#");
			        aktStringBuilder.append(event_name + "\n");
			    	aktStringBuilder.append(aktDateFormatter.format(aktEventDate) + " - ");
			    	aktStringBuilder.append(aktRessourceStartTime);
			    	
			        /* Replace with List when build */
			        aktFoundObjectsForListViewArray.add(aktStringBuilder.toString());
			        
			        Log.i("JSON Object fetch -> "+i , event_name + " - " + event_description + " - " + aktDateFormatter.format(aktEventDate) + " - " + aktRessourceStartTime);
					
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
	    
		} else if (parserComponent.equals("location")) {
			
			/* If a Location has to be parsed */
			
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "locationHandlerSet" :"locationHandler";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
					int location_id = aktJSONObject.getInt("location_id");
			        String location_name = aktJSONObject.getString("location_name");
			        String location_zip = aktJSONObject.getString("location_zip");
			        String location_town = aktJSONObject.getString("location_town");
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(location_id + "#");
			        aktStringBuilder.append(location_name+"\n");
			    	aktStringBuilder.append(location_zip+" ");
			    	aktStringBuilder.append(location_town);
			    	
			        /* Replace with List when build */
			        aktFoundObjectsForListViewArray.add(aktStringBuilder.toString());
			        
			        Log.i("JSON Object fetch -> "+i , location_name + " - " + location_zip + " - " + location_town );
					
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
			
		} else if (parserComponent.equals("locationCategory")) {
			
			/* If the Location Categories have to be parsed */
			
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "locationHandlerCategorySet" :"locationHandlerCategory";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
					int location_category_id = aktJSONObject.getInt("location_category_id");
			        String location_category_name = aktJSONObject.getString("location_category_name");
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(location_category_id + "#");
			        aktStringBuilder.append(location_category_name);
			    	
			    	
			        /* Replace with List when build */
			        aktFoundObjectsForListViewArray.add(aktStringBuilder.toString());
			        
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
			
		} else if (parserComponent.equals("eventCategory")) {
			
			/* If the Location Categories have to be parsed */
			
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "eventHandlerCategorySet" :"eventHandlerCategory";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
					int event_category_id = aktJSONObject.getInt("event_category_id");
			        String event_category_name = aktJSONObject.getString("event_category_name");
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(event_category_id + "#");
			        aktStringBuilder.append(event_category_name);
			    	
			        /* Replace with List when build */
			        aktFoundObjectsForListViewArray.add(aktStringBuilder.toString());
			        
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
			
		}
		
		return aktFoundObjectsForListViewArray;
		
	}

	/**
	 * 
	 * @param jsonToParse
	 * @param parserComponent
	 * @param fetchMultipleResults
	 * @return
	 */
	public static ArrayList<String> parseJSONDataToArrayList (String jsonToParse, String parserComponent, boolean fetchMultipleResults) {
		
		/* Parsing the Result within the Found Events into a JSON Object */
	    JSONArray JSONResultArray = null;
	    JSONObject aktJSONObject = null;
	    StringBuilder aktStringBuilder = null;
	    ArrayList<String> aktFoundResultsForArrayList = new ArrayList<String>();
	    String jSonArrayName = "";
	    
		/* If a Event has to be parsed */
		if(parserComponent.equals("event")) {
		    
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "eventHandlerSet" :"eventHandler";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
					int event_id = aktJSONObject.getInt("event_id");
			        String event_name = aktJSONObject.getString("event_name");
			        String event_description = aktJSONObject.getString("event_description");
			        long event_start_date = aktJSONObject.getLong("event_start_date");
			        long event_start_time = aktJSONObject.getLong("event_start_time");	
			        String event_creator_user_id =  aktJSONObject.getString("event_creator_user_id");
			        
			        /* Format Date */
			        Date aktEventDate = new java.util.Date(event_start_date*1000);
			        SimpleDateFormat aktDateFormatter = new SimpleDateFormat("E dd MMM yyyy");
			        
			        /* Format Time */
			        int aktRessourceHours   = (int) ((event_start_time / 3600));
			        int aktRessourceMinutes = (int) ((event_start_time - (aktRessourceHours * 3600)) / 60 );
			        
			        /*Add missing hour because of GMT+1*/
			        aktRessourceHours += 1;
			        
			        /* Placeholder for Minutes converter in case of 0 Minutes */
			        String aktRessourceMinutesString = "";
			        
			        /* Check if minutes are 0, because in INT there is no possibility of Doubled zero */
			        aktRessourceMinutesString = aktRessourceMinutes == 0 ? "00" : aktRessourceMinutes+"";
			        
			        String aktRessourceStartTime = aktRessourceHours + ":" + aktRessourceMinutesString + " Uhr#";
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(event_name + "#");
			    	aktStringBuilder.append(aktDateFormatter.format(aktEventDate) + "#");
			    	aktStringBuilder.append(aktRessourceStartTime + "#");
			    	aktStringBuilder.append(event_description + "#");
			    	aktStringBuilder.append(event_creator_user_id + "#");
			    	aktStringBuilder.append(event_id + "#");
			    	aktStringBuilder.append(event_start_date + "#");
			    	aktStringBuilder.append(event_start_time + "#");
			    	
			        /* Replace with List when build */
			        aktFoundResultsForArrayList.add(aktStringBuilder.toString());
			        
			        Log.i("JSON Object fetch -> "+i , event_name + " - " + event_description + " - " + aktDateFormatter.format(aktEventDate) + " - " + aktRessourceStartTime);
					
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
	    
		} else if (parserComponent.equals("location")) {
			
			/* If a Location has to be parsed */
			
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "locationHandlerSet" :"locationHandler";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			} catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}    
		    
		    /* Fetch all included JSON Objects */
		    for(int i = 0 ; i < JSONResultArray.length() ; i++){
		    	try {
		    		aktStringBuilder = new StringBuilder();
		    		
					aktJSONObject = JSONResultArray.getJSONObject(i);
					
			        String location_name = aktJSONObject.getString("location_name");
			        String location_adress = aktJSONObject.getString("location_adress");
			        String location_zip = aktJSONObject.getString("location_zip");
			        String location_town = aktJSONObject.getString("location_town");
			        String location_description = aktJSONObject.getString("location_description");
			        String location_longitude = aktJSONObject.getString("location_longitude");
			        String location_latitude = aktJSONObject.getString("location_latitude");
			        String location_telefone = aktJSONObject.getString("location_telefone");
			        String location_fax = aktJSONObject.getString("location_fax");
			        String location_email = aktJSONObject.getString("location_email");
			        String location_website = aktJSONObject.getString("location_website");
			        String location_creator_user_id = aktJSONObject.getString("location_creator_user_id");
			        
			        /* Build String for Listview Entry */
			        aktStringBuilder.append(location_name + "#");
			        aktStringBuilder.append(location_adress + "#");
			        aktStringBuilder.append(location_zip + "#");
			        aktStringBuilder.append(location_town + "#");
			    	aktStringBuilder.append(location_description + "#");
			    	aktStringBuilder.append(location_telefone + "#");   
			    	aktStringBuilder.append(location_fax + "#");
			    	aktStringBuilder.append(location_email + "#");
			    	aktStringBuilder.append(location_website + "#");
			    	aktStringBuilder.append(location_longitude + "#");
			    	aktStringBuilder.append(location_latitude + "#");
			    	aktStringBuilder.append(location_creator_user_id);
			    	
			        /* Replace with List when build */
			        aktFoundResultsForArrayList.add(aktStringBuilder.toString());
					
				} catch (JSONException e) {
					Log.e("JSON Object fetch", e.getMessage());
				}
		    }
			
		} else if (parserComponent.equals("user")) {
			
			/* If a Location has to be parsed */
			
			/* Select if single or multiple event has been fetched */
			jSonArrayName = fetchMultipleResults ? "userHandlerSet" :"userHandler";
			
		    try {
			    JSONObject foundResultsJSON = new JSONObject(jsonToParse);
			    JSONResultArray = foundResultsJSON.getJSONArray(jSonArrayName); 
			    
			    /* Fetch all included JSON Objects */
			    for(int i = 0 ; i < JSONResultArray.length() ; i++){
			    	try {
			    		aktStringBuilder = new StringBuilder();
			    		
						aktJSONObject = JSONResultArray.getJSONObject(i);
						
				        String user_id = aktJSONObject.getString("user_id");
				        String user_forename = aktJSONObject.getString("user_forename");
				        String user_surname = aktJSONObject.getString("user_surname");
				        String user_email = aktJSONObject.getString("user_email");
				        String user_pass = aktJSONObject.getString("user_pass");
				        String user_rights_id = aktJSONObject.getString("user_rights_id");
				        
				        /* Build String for Listview Entry */
				        aktStringBuilder.append(user_id + "#");
				        aktStringBuilder.append(user_forename + "#");
				        aktStringBuilder.append(user_surname + "#");
				        aktStringBuilder.append(user_email + "#");
				    	aktStringBuilder.append(user_pass + "#");
				    	aktStringBuilder.append(user_rights_id + "#"); 
				    	
				        /* Replace with List when build */
				        aktFoundResultsForArrayList.add(aktStringBuilder.toString());
						
					} catch (JSONException e) {
						Log.e("JSON Object fetch", e.getMessage());
					}
			    }
		    
		    } catch (JSONException e) {
				Log.e("JSON Collection fetch", e.getMessage());
			}
			
		}
		
		return aktFoundResultsForArrayList;
		
	}

	public static JSONObject createJSONDataFromHashMap (HashMap newRessourceData) {
		/* TODO BUILD JSON PARSER */
		return new JSONObject();
	}
}

